package com.ruoyi.common.utils;

import java.util.*;

public class ReferralCodeGenerator {
    // 字符池 - 去除了容易混淆的字符(0,O,1,I,L等)
    private static final String CHARACTERS = "23456789ABCDEFGHJKMNPQRSTUVWXYZ";
    private static final int CODE_LENGTH = 6; // 推荐码长度
    private static final Random random = new Random();

    /**
     * 生成随机推荐码
     * @return 6位推荐码
     */
    public static String generateReferralCode() {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            code.append(CHARACTERS.charAt(randomIndex));
        }
        return code.toString();
    }

    /**
     * 批量生成不重复的推荐码
     * @param count 需要生成的数量
     * @return 推荐码列表
     */
    public static List<String> generateUniqueCodes(int count) {
        Set<String> codes = new HashSet<>();
        while (codes.size() < count) {
            String code = generateReferralCode();
            codes.add(code);
        }
        return new ArrayList<>(codes);
    }

    /**
     * 生成带前缀的推荐码
     * @param prefix 前缀字符串
     * @return 带前缀的推荐码
     */
    public static String generateCodeWithPrefix(String prefix) {
        if (prefix == null || prefix.isEmpty()) {
            return generateReferralCode();
        }
        return prefix + generateReferralCode();
    }

    /**
     * 验证推荐码格式是否正确
     * @param code 待验证的推荐码
     * @return 是否有效
     */
    public static boolean validateCode(String code) {
        if (code == null || code.length() != CODE_LENGTH) {
            return false;
        }
        return code.chars().allMatch(ch -> CHARACTERS.indexOf(ch) >= 0);
    }

    // 使用示例
    public static void main(String[] args) {
        // 生成单个推荐码
        String code = generateReferralCode();
        System.out.println("单个推荐码: " + code);

        // 批量生成5个不重复的推荐码
        List<String> codes = generateUniqueCodes(5);
        System.out.println("批量推荐码: " + codes);

        // 生成带前缀的推荐码
        String prefixCode = generateCodeWithPrefix("VIP");
        System.out.println("带前缀推荐码: " + prefixCode);

        // 验证推荐码
        boolean isValid = validateCode(code);
        System.out.println("推荐码验证结果: " + isValid);
    }
}